//
//  MyFriendViewController.m
//  安好
//
//  Created by 马晓良 on 14-12-3.
//  Copyright (c) 2014年 lianchuangbrother. All rights reserved.
//

#import "MyFriendViewController.h"
#import "MyFirendCell.h"
#import "SearchFriendCell.h"
#import "MyFirendHeaderView.h"
#import "MyFirendDataManager.h"
#import "FirendDetailViewController.h"
#import "FKSearchBar.h"
#import "MyFirendData.h"
#import "MyNewFirendViewController.h"
#import "UserId.h"
#import "PopoverView.h"
#import "AddFirendViewController.h"
#import "MyPeerListViewController.h"
@interface MyFriendViewController ()<UITableViewDataSource,UITableViewDelegate,FKSearchBarDelegate>
{
    FKSearchBar * illSeachBar;
    BOOL LoadingWay;
    BOOL search;
    NSInteger integers;
}
/**
 *  好友列表
 */
@property (strong, nonatomic) IBOutlet UITableView *myFriendTableView;
/**
 *  好友数据数组
 */
@property (nonatomic, strong) NSMutableArray *firendDataArray;
/**
 *  存放要删除的
 */
@property (nonatomic, strong) NSString *uidStr;
/**
 *  NSUserDefult
 */
@property (nonatomic, strong) NSUserDefaults *userDefault;
@property (nonatomic, strong) NSUserDefaults *defaults;
/**
 *  关注数
 */
@property (nonatomic, strong) NSString *firendCountStr;
@property (nonatomic, assign) BOOL isSearch;

/**
 *  搜索页数
 */
@property (nonatomic, assign) NSInteger firendPage;
/**
 *  搜索的字
 */
@property (nonatomic, strong) NSString *searchFirends;
/**
 *  搜索获取的数据存放的数组
 */
@property (nonatomic, strong) NSMutableArray *searchFirendsArray;
/**
 *  获取全局对象用于删除操作
 */
@property (nonatomic, strong) MyFirendData *myfirendDataSource;

@property (nonatomic, strong) NSIndexPath *firendIndexPath;
@property (nonatomic, strong) NSMutableArray *firstLetterArr;
@end

@implementation MyFriendViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [[MyFirendDataManager shareInstance] createTableWithName:@"myFirendTable"];
    self.myFriendTableView.dataSource = self;
    self.myFriendTableView.delegate = self;
    [self setNaviBarAttribute];
    self.navigationItem.title = @"我的好友";
    //  标签颜色
    self.myFriendTableView.sectionIndexBackgroundColor = [UIColor clearColor];
    
    self.myFriendTableView.sectionIndexColor = [ClassMethodsViewController colorWithHexString:NACIGATIONBAR_BACKGROUNDCOLOR_16];
    self.userDefault = [NSUserDefaults standardUserDefaults];
    [[[MyFirendDataManager shareInstance] firendDic] removeAllObjects];
    
    
    self.myFriendTableView.backgroundColor = [ClassMethodsViewController colorWithHexString:BACK_BACKGROUNDCOLOR_16];
    // Do any additional setup after loading the view from its nib.
}


- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [[[MyFirendDataManager shareInstance] firendDic] removeAllObjects];
    //  记录当前的uid
    self.defaults = [NSUserDefaults standardUserDefaults];
    [self.defaults setObject:[UserId shareUid].uidStr forKey: @"myCurrentUid"];
    NSString *str = [self.defaults objectForKey:@"myCurrentUid"];
    if (str.length < 1) {
        // 判断是否是要获取本地数据  是的话赋值100
        integers = 100;
        NSArray *dataArray = [[MyFirendDataManager shareInstance] searchMyFirendInfo:[self.userDefault objectForKey:@"uid"]];
        MyNSLog("%@",dataArray);
        //  从数据库中获取数据
        for (MyFirendData *objc in dataArray) {
            [[MyFirendDataManager shareInstance] addNewFirendItem:objc];
            MyNSLog("%@", objc.username);
        }
//        [self loadDataFromInternet];
        [self firendCount];
        return;
    }
    MyNSLog("%@==and==%@", str,[self.userDefault objectForKey:@"uid"]);
    if (![str isEqualToString:[self.userDefault objectForKey:@"uid"]]) {
        // 为了防止用户在其他手机上登录，所有在每次登录后都要删除数据库中表的有关本用户的数据信息
        [self loadData];
        MyNSLog("走这个了");
        //  记录上一个uid
        [self.userDefault setValue:[UserId shareUid].uidStr forKey:@"uid"];
        [self firendCount];
    }else{
        //  判断是不是重新登陆了
        if ([self.userDefault objectForKey:@"landing"] != nil) {
            [self.userDefault removeObjectForKey:@"landing"];
            [[MyFirendDataManager shareInstance] deleteMyFirendInfo:[UserId shareUid].uidStr];
            [self loadData];
            if ([[MyFirendDataManager shareInstance] searchMyFirendInfo:[self.userDefault objectForKey:@"uid"]].count == 0) {
                [self.myFriendTableView addHeaderWithTarget:self action:@selector(loadData)];
            }else{
                [self.myFriendTableView addHeaderWithTarget:self action:@selector(timerAction)];
            }
        }else{
            integers = 100;
            NSArray *dataArray = [[MyFirendDataManager shareInstance] searchMyFirendInfo:[self.userDefault objectForKey:@"uid"]];
            MyNSLog("%@", [self.userDefault objectForKey:@"uid"]);
            MyNSLog("%@", dataArray);
            if (dataArray.count == 0) {
                [self.myFriendTableView addHeaderWithTarget:self action:@selector(loadData)];
            }else{
                [self.myFriendTableView addHeaderWithTarget:self action:@selector(timerAction)];
            }
            //  从数据库中获取数据
            for (MyFirendData *objc in dataArray) {
                [[MyFirendDataManager shareInstance] addNewFirendItem:objc];
                
            }
        }
        [self firendCount];
    }
    
//    [self firendCount];
}

- (void)timerAction{
    [self performSelector:@selector(shuaxin) withObject:nil afterDelay:0.7];
    
}

- (void)shuaxin{
    [self.myFriendTableView headerEndRefreshing];
}



- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [[[MyFirendDataManager shareInstance] firendDic] removeAllObjects];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - 设置naviBar 并实现左右naviBar button方法 -
- (void)setNaviBarAttribute{
    /**
     *  设置左NaviBar和右naviBar
     */
    UIButton *leftButton = [UIButton buttonWithType:UIButtonTypeCustom];
    leftButton.frame = CGRectMake(0, 0, 23, 23);
    [leftButton setImage:[UIImage imageNamed:@"公用_返回"] forState:UIControlStateNormal];
    [leftButton addTarget:self action:@selector(handleLeftButtonAction) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:leftButton];
    self.navigationItem.leftBarButtonItem = leftBarButtonItem;
    
    
    UIButton *rightButton = [UIButton buttonWithType:UIButtonTypeCustom];
    rightButton.frame = CGRectMake(0, 0, 60, 23);
    [rightButton setTitle:@"添加好友" forState:UIControlStateNormal];
    rightButton.titleLabel.font = [UIFont systemFontOfSize:15];
    [rightButton addTarget:self action:@selector(handleRightButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:rightButton];
}

/**
 *  返回主页面
 */
- (void)handleLeftButtonAction{
    [self.navigationController popViewControllerAnimated:YES];
}

/**
 *  完成(返回并传值)
 */
- (void)handleRightButtonAction:(UIButton *)sender{
    AddFirendViewController *addFirendVC = [[AddFirendViewController alloc] init];
    [self.navigationController pushViewController:addFirendVC animated:YES];
    /** 下拉的列表
    CGPoint point = CGPointMake(sender.frame.origin.x + sender.frame.size.width/2, 64);
    NSArray *titles = @[@"添加好友", @"对话记录"];
    NSArray *images = @[@"圈子_添加选项", @"圈子_管理选项"];
    PopoverView *pop = [[PopoverView alloc] initWithPoint:point titles:titles images:images];
    pop.selectRowAtIndex = ^(NSInteger index){
        MyNSLog("select index:%d", index);
        switch (index) {
            case 0:
            {
                MyNSLog("第一个");
                AddFirendViewController *addFirendVC = [[AddFirendViewController alloc] init];
                [self.navigationController pushViewController:addFirendVC animated:YES];
            }
                break;
            case 1:
            {
                MyNSLog("第二个");
                MyPeerListViewController *myPeerVC = [[MyPeerListViewController alloc] init];
                [self.navigationController pushViewController:myPeerVC animated:YES];
            }
                break;
                
            default:
                break;
        }
    };
    [pop show];
     */
}


#pragma mark - tableView的代理方法 -

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    //  返回区的数目
    return [[MyFirendDataManager shareInstance] numberOfSections] + 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (section == 0) {
        return 1;
    }else{
         return [[MyFirendDataManager shareInstance] numberOfFirendItemsInSection:section - 1];
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0) {
        if (kScreenWidth == 414) {
            return 97;
        }else{
            return 88;
        }
    }else{
        return 64;
    }
}


- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if (section == 0) {
        return 0;
    }else{
        return 20;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 0.5;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 0.5)];
    view.backgroundColor = [UIColor colorWithRed:221/ 255.0 green:221/255.0 blue:221/255.0 alpha:1];
    return view;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    MyFirendHeaderView *headerView = [[[NSBundle mainBundle] loadNibNamed:@"MyFirendHeaderView" owner:self options:nil] lastObject];
    headerView.backgroundColor = [UIColor colorWithRed:237.0/255 green:237.0/255 blue:237.0/255 alpha:1];
    headerView.initialLabel.text = [[MyFirendDataManager shareInstance] titleStringForSection:section - 1];
    headerView.footView.frame = CGRectMake(0, 19.75, kScreenWidth, 0.25);
    headerView.footView.backgroundColor = [UIColor colorWithRed:221/ 255.0 green:221/255.0 blue:221/255.0 alpha:1];
    return headerView;
}


//设置tableView每一行的编辑样式
-(UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0) {
        return UITableViewCellEditingStyleNone;
    }else return UITableViewCellEditingStyleDelete;
        
}


//设置删除时显示的文字
-(NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath{
    return @"删除";
}

-(BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0) {
        return NO;
    }else return YES;
}

-(BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0) {
        return NO;
    }else return YES;
}


//触发删除按钮的方法
-(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath{
    self.firendIndexPath = indexPath;
    if ([UserId shareUid].uidStr.length > 1) {
        if (indexPath == 0) {
        }else{
            self.myfirendDataSource = [[MyFirendDataManager shareInstance] firendItemAtIndexPath:indexPath];
            self.uidStr = self.myfirendDataSource.uid;
            //  执行删除操作
            [self deleteMyfirend];
        }
    }else{
        
    }
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    MyFirendCell *cell = [tableView dequeueReusableCellWithIdentifier:@"myFirendCell"];
    SearchFriendCell *searchCell = [tableView dequeueReusableCellWithIdentifier:@"searchFirendCell"];
    if (!cell) {
        if (kScreenWidth == 414) {
            cell = [[[NSBundle mainBundle] loadNibNamed:@"MyFirendCell" owner:self options:nil] lastObject];
        }else{
            cell = [[[NSBundle mainBundle] loadNibNamed:@"MyFirendCell" owner:self options:nil] firstObject];
        }
    }
    if (!searchCell) {
        if (kScreenWidth == 414) {
            searchCell = [[[NSBundle mainBundle] loadNibNamed:@"SearchFriendCell" owner:self options:nil] lastObject];
        }else{
            searchCell = [[[NSBundle mainBundle] loadNibNamed:@"SearchFriendCell" owner:self options:nil] firstObject];
        }
    }
    if (indexPath.section == 0) {
        illSeachBar = [[FKSearchBar alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, 44)];
        illSeachBar.fkSearchRequestDelegate = self;
        illSeachBar.searchTextField.text = self.searchFirends;
        [searchCell.contentView addSubview: illSeachBar];
        if (kScreenWidth == 414) {
            searchCell.redNumLabel.frame = CGRectMake(kScreenWidth - 39, 58, 24, 24);
            searchCell.redNumLabel.layer.masksToBounds = YES;
            searchCell.redNumLabel.layer.cornerRadius = 12;
        }else{
            searchCell.redNumLabel.frame = CGRectMake(kScreenWidth - 35, 55, 20, 20);
            searchCell.redNumLabel.layer.masksToBounds = YES;
            searchCell.redNumLabel.layer.cornerRadius = 10;
        }
        [searchCell.jumpAnotherPage addTarget:self action:@selector(jumpAnotherPageAction:) forControlEvents:UIControlEventTouchUpInside];
        if ([self.firendCountStr intValue] > 0) {
            searchCell.redNumLabel.hidden = NO;
            if ([self.firendCountStr  integerValue] >= 1000) {
                searchCell.redNumLabel.text = @">1k";
            }else{
               searchCell.redNumLabel.text = [NSString stringWithFormat:@"%@",self.firendCountStr];
            }
        }else{
            searchCell.redNumLabel.hidden = YES;
            MyNSLog("%@", searchCell.redNumLabel.text);
        }
        return searchCell;
    }else{
        MyFirendData *myFirendData = [[MyFirendDataManager shareInstance] firendItemAtIndexPath:indexPath];
        
        cell.headerImageView.layer.masksToBounds = YES;
        cell.headerImageView.layer.cornerRadius = 3.0f;

        if (integers != 100) {
            [cell.headerImageView setImageWithURL:[NSURL URLWithString:myFirendData.avatar] placeholderImage:[UIImage imageNamed:@"默认头像"]];
        }else{
            MyNSLog("id he muuid %@%@",myFirendData.uid,myFirendData.myuid);
            if ([[MyFirendDataManager shareInstance] judgeImageExist:myFirendData.uid withMyUid:myFirendData.myuid]) {
                cell.headerImageView.image = [[MyFirendDataManager shareInstance] loadImageFromDocument:myFirendData.uid withMyUid:myFirendData.myuid];
            }else{
                cell.headerImageView.image = [UIImage imageNamed:@"默认头像"];
            }

        }
        cell.firendNameLabel.text = myFirendData.username;
        return cell;
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0) {
        
    }else{
         MyFirendData *myFirendData = [[MyFirendDataManager shareInstance] firendItemAtIndexPath:indexPath];
        FirendDetailViewController *firendDetailVC = [[FirendDetailViewController alloc] init];
        firendDetailVC.firendId = myFirendData.uid;
        [self.navigationController pushViewController:firendDetailVC animated:YES];
    }
}

//  索引
- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView{
    NSArray *array = [[[MyFirendDataManager shareInstance] firendDic] allKeys];
     NSArray *orderedArray = [array sortedArrayUsingSelector:@selector(compare:)];
    MyNSLog("###########%@", [[MyFirendDataManager shareInstance] firendDic]);
    return orderedArray;
}

-(void)tableView:(UITableView *)tableView accessoryButtonTappedForRowWithIndexPath:(NSIndexPath *)indexPath{
    MyNSLog("单元格右侧的辅助视图按钮触发了%d %d",indexPath.section,indexPath.row);
}


/* 点击目录
-(NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index
{
    // 获取所点目录对应的indexPath值
    NSIndexPath *selectIndexPath = [NSIndexPath indexPathForRow:0 inSection:index];
    
    // 让table滚动到对应的indexPath位置
    [tableView scrollToRowAtIndexPath:selectIndexPath atScrollPosition:UITableViewScrollPositionBottom animated:YES];
    
    return index;
}
*/

#pragma mark - 网络数据加载 -

- (void)loadData{
    [self showActionView];
    //postUrl
    NSString *postURL = [NSString stringWithFormat:@"%@user/friends/",kBaseURL];
    //post参数列表
    NSDictionary *parameters = @{@"platform": kPlatform,@"version":kVersion};
    //网络请求管理者
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    //开始请求
    [manager POST:postURL parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject)
     {
        NSNumber * statusNum = [responseObject objectForKey:@"status"];
        //用NSNumberFormatter把 NSNumber类型的数字-->转成字符串
        NSNumberFormatter* numberFormatter = [[NSNumberFormatter alloc] init];
        NSString * statusString = [numberFormatter stringFromNumber:statusNum];//得到字符串对象: "0" / "1"
         [self hiddenActionView];
        if ([statusString isEqualToString:@"0"])
        {
            [self shouLabel:@"暂无好友"]; //失败
        }else
        {
            NSArray *encyDic = [responseObject objectForKey:@"data"];
            MyNSLog("===###==%@", encyDic);
            for (NSDictionary *dic in encyDic)
            {
                MyFirendData *myFirendObjc = [[MyFirendData alloc] init];
                myFirendObjc.myuid = [UserId shareUid].uidStr;
                [myFirendObjc setValuesForKeysWithDictionary:dic];
                //  单例对数据操作
                [[MyFirendDataManager shareInstance] addNewFirendItem:myFirendObjc];
                
                 [[MyFirendDataManager shareInstance] addNewFirendInfo:myFirendObjc];
                
                 [[MyFirendDataManager shareInstance] setImagePath:myFirendObjc.avatar withUid:myFirendObjc.uid withMyUid:myFirendObjc.myuid];
                
                if ([[MyFirendDataManager shareInstance] searchMyFirendInfo:[self.userDefault objectForKey:@"uid"]].count != 0) {
                    [self.myFriendTableView headerEndRefreshing];
                    [self.myFriendTableView removeHeader];
                    [self.myFriendTableView addHeaderWithTarget:self action:@selector(timerAction)];
                }
            }
            //刷新table
            [self.myFriendTableView reloadData];
        }
         [self.myFriendTableView headerEndRefreshing];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        [[[MyFirendDataManager shareInstance] firendDic] removeAllObjects];
        NSArray *dataArray = [[MyFirendDataManager shareInstance] searchMyFirendInfo:[self.userDefault objectForKey:@"uid"]];
        MyNSLog("%@", dataArray);
        //  从数据库中获取数据
        for (MyFirendData *objc in dataArray) {
            [[MyFirendDataManager shareInstance] addNewFirendItem:objc];
            MyNSLog("%@", objc);
        }
        [self.myFriendTableView reloadData];
        [self hiddenActionView];
        [self.myFriendTableView headerEndRefreshing];
    }];
}

//  也就是取消关注
- (void)deleteMyfirend{
    [self showActionView];
    //postUrl
    NSString *postURL = [NSString stringWithFormat:@"%@user/unfollowuser/",kBaseURL];
    //post参数列表
    NSDictionary *parameters = @{@"platform": kPlatform,@"version":kVersion,@"uid":self.uidStr};
    //网络请求管理者
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    //开始请求
    [manager POST:postURL parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject)
     {
         NSNumber * statusNum = [responseObject objectForKey:@"status"];
         //用NSNumberFormatter把 NSNumber类型的数字-->转成字符串
         NSNumberFormatter* numberFormatter = [[NSNumberFormatter alloc] init];
         NSString * statusString = [numberFormatter stringFromNumber:statusNum];//得到字符串对象: "0" / "1"
         [self hiddenActionView];
         MyNSLog("%@",responseObject);
         if ([statusString isEqualToString:@"0"])
         {
             //            [self shouLabel:@"暂无内容"]; //失败
             [self showCustomHudSingleLine:@"删除失败"];
             
         }else
         {
             MyNSLog("删除成功");
             NSArray *key = [[[MyFirendDataManager shareInstance] firendDic] allKeys];
             NSArray *orderedArray = [key sortedArrayUsingSelector:@selector(compare:)];
             NSString *oneKey = [orderedArray objectAtIndex:self.firendIndexPath.section - 1];
             // 得到key对应的数组
             NSMutableArray *groupArr = [[[MyFirendDataManager shareInstance] firendDic] objectForKey:oneKey];
             
             if ([groupArr count] == 1) {
                 [[[MyFirendDataManager shareInstance] firendDic] removeObjectForKey:oneKey];
                 MyNSLog("&&&&&&&&&&&&&&%@", oneKey);
                 
                 MyNSLog("%@", [[MyFirendDataManager shareInstance] firendDic]);
             }
             //  从数据库删除数据
             [[MyFirendDataManager shareInstance] deleteMyFirendInfo:self.myfirendDataSource.uid withMyUid:self.myfirendDataSource.myuid];
             
             [[MyFirendDataManager shareInstance] deleteFirendItem:self.myfirendDataSource];
             // 删除本地的用户头像
             [[MyFirendDataManager shareInstance] deleteImage:self.myfirendDataSource.uid withMyUid:self.myfirendDataSource.myuid];
             for (NSString *key in orderedArray) {
                 if ([[[[MyFirendDataManager shareInstance] firendDic] objectForKey:key] count] == 0) {
                     [[[MyFirendDataManager shareInstance] firendDic] removeObjectForKey:key];
                 }
             }
             [self.myFriendTableView reloadData];
         }
     } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
         [self hiddenActionView];
     }];
}


//  同步网页端
- (void)loadDataFromInternet{
    //postUrl
    NSString *postURL = [NSString stringWithFormat:@"%@user/followlog/",kBaseURL];
    //post参数列表
    NSDictionary *parameters = @{@"platform": kPlatform,@"version":kVersion};
    //网络请求管理者
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    //开始请求
    [manager POST:postURL parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject)
     {
         NSNumber * statusNum = [responseObject objectForKey:@"status"];
         //用NSNumberFormatter把 NSNumber类型的数字-->转成字符串
         NSNumberFormatter* numberFormatter = [[NSNumberFormatter alloc] init];
         NSString * statusString = [numberFormatter stringFromNumber:statusNum];//得到字符串对象: "0" / "1"
         
         if ([statusString isEqualToString:@"0"])
         {
//             [self showCustomHudSingleLine:@"同步失败"];
         }else
         {
             NSArray *encyDic = [responseObject objectForKey:@"data"];
             for (NSDictionary *dic in encyDic)
             {
                 MyFirendData *myFirendObjc = [[MyFirendData alloc] init];
                 myFirendObjc.myuid = [UserId shareUid].uidStr;
                 [myFirendObjc setValuesForKeysWithDictionary:dic];
                 MyNSLog("$$$$$$$$$$$$$$$$%@", myFirendObjc.username);
                 //  单例对数据操作
                 if ([myFirendObjc.type isEqualToString:@"1"]) {
                     [[MyFirendDataManager shareInstance] addNewFirendItem:myFirendObjc];
                     // 向数据库添加数据
                     [[MyFirendDataManager shareInstance] addNewFirendInfo:myFirendObjc];
                     //  存放头像
                     [[MyFirendDataManager shareInstance] setImagePath:myFirendObjc.avatar withUid:myFirendObjc.uid withMyUid:myFirendObjc.myuid];
                 }else{
                     //  删除数据
                     [[MyFirendDataManager shareInstance] deleteMyFirendInfo:myFirendObjc.uid withMyUid:myFirendObjc.myuid];
                     [[MyFirendDataManager shareInstance] deleteFirendItem:myFirendObjc];
                     
                     [[MyFirendDataManager shareInstance] deleteImage:myFirendObjc.uid withMyUid:myFirendObjc.myuid];
                  }
                 MyNSLog("已经更新了了");
             }
             //刷新table
             [self.myFriendTableView reloadData];
         }
         
     } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
         [[[MyFirendDataManager shareInstance] firendDic] removeAllObjects];
         NSArray *dataArray = [[MyFirendDataManager shareInstance] searchMyFirendInfo:[self.userDefault objectForKey:@"uid"]];
         //  从数据库中获取数据
         for (MyFirendData *objc in dataArray) {
             [[MyFirendDataManager shareInstance] addNewFirendItem:objc];
             MyNSLog("%@", objc);
         }
         [self.myFriendTableView reloadData];
         MyNSLog("======失败");
     }];
}


//  关注我的好友个数
- (void)firendCount{
    [self showActionView];
    //postUrl
    NSString *postURL = [NSString stringWithFormat:@"%@user/byfollowingcount/",kBaseURL];
    //post参数列表
    NSDictionary *parameters = @{@"platform": kPlatform,@"version":kVersion};
    //网络请求管理者
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    //开始请求
    [manager POST:postURL parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject)
     {
         NSNumber * statusNum = [responseObject objectForKey:@"status"];
         //用NSNumberFormatter把 NSNumber类型的数字-->转成字符串
         NSNumberFormatter* numberFormatter = [[NSNumberFormatter alloc] init];
         NSString * statusString = [numberFormatter stringFromNumber:statusNum];//得到字符串对象: "0" / "1"
         [self hiddenActionView];
         if ([statusString isEqualToString:@"0"])
         {
             //            [self shouLabel:@"暂无内容"]; //失败
//             [self showCustomHudSingleLine:@"新的好友数据获取失败"];
             alertContent([responseObject objectForKey:@"msg"]);
             
         }else
         {
              NSDictionary *encyDic = [responseObject objectForKey:@"data"];
             if (encyDic.count == 0) {
                 
             }else{
                 self.firendCountStr = [encyDic objectForKey:@"count"];
             }
             
             MyNSLog("返回的结果===%@", responseObject);
             MyNSLog("关注我的好友的个数%@", self.firendCountStr);
         }
         [self.myFriendTableView reloadData];
     } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
         [self hiddenActionView];
         [self.myFriendTableView reloadData];
     }];
    [self loadDataFromInternet];
}



#pragma mark - 新好友的执行方法 -
- (void)jumpAnotherPageAction:(UIButton *)sender{
    if ([self.firendCountStr intValue] > 0) {
        MyNewFirendViewController *myNewFirendVC = [[MyNewFirendViewController alloc] init];
        [self.navigationController pushViewController:myNewFirendVC animated:YES];
    }
}


#pragma mark - 搜索框的执行方法 -
/**
 *  FKSearch的delegate
 */
- (void)VoiceConversion
{
    [illSeachBar.searchTextField resignFirstResponder];
    [self starVoice];
}
- (void)voice:(NSString *)voice
{
    illSeachBar.searchTextField.text = voice;
    self.isSearch = YES;
    self.firendPage = 1;
    self.searchFirends = voice;
    [self getSQLFuzzySearch];
}
- (void)SearchString
{
    [illSeachBar.searchTextField resignFirstResponder];
    self.isSearch = YES;
    self.firendPage = 1;
    MyNSLog("搜索");
    self.searchFirends = illSeachBar.searchTextField.text;
    [self getSQLFuzzySearch];
}

- (void)getSQLFuzzySearch{
    if (self.isSearch == YES){
        if ([[[MyFirendDataManager shareInstance] firendDic] count] != 0){
            [[[MyFirendDataManager shareInstance] firendDic] removeAllObjects];
        }
    }
    NSArray *dataArray = [[MyFirendDataManager shareInstance] searchMYfirendInfoWithUid:[self.userDefault objectForKey:@"uid"] withString:self.searchFirends];
    for (MyFirendData *objc in dataArray) {
        [[MyFirendDataManager shareInstance] addNewFirendItem:objc];
    }
    MyNSLog("%@", self.searchFirends);

    illSeachBar.searchTextField.text = self.searchFirends;
    [self.myFriendTableView reloadData];
}


#pragma mark - 懒加载 -
- (MyFirendData *)myfirendDataSource{
    if (_myfirendDataSource == nil) {
        _myfirendDataSource = [[MyFirendData alloc] init];
    }
    return _myfirendDataSource;
}

- (NSMutableArray *)searchFirendsArray{
    if (_searchFirendsArray == nil) {
        self.searchFirendsArray = [NSMutableArray array];
    }
    return _searchFirendsArray;
}

- (NSMutableArray *)firendDataArray{
    if (_firendDataArray == nil) {
        self.firendDataArray = [NSMutableArray array];
    }
    return _firendDataArray;
}

- (NSIndexPath *)firendIndexPath{
    if (_firendIndexPath == nil) {
        _firendIndexPath = [[NSIndexPath alloc] init];
    }
    return _firendIndexPath;
}

- (NSMutableArray *)firstLetterArr{
    if (_firstLetterArr == nil) {
        _firstLetterArr = [NSMutableArray array];
    }
    return _firstLetterArr;
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
